#include <stdio.h>
#include <omp.h>
#include <stdlib.h>
#include <time.h>

void swap(int* a, int* b){
    int t = *a;
    *a = *b;
    *b = t;
}

void CreateData(int *arr, int size){
    srand(0);
    for (int i = 0; i < size; ++i)
        arr[i] = rand() % size;
}

void bubbleSort(int* data, int size)
{
    int i, j, temp;
    int thread_num = omp_get_max_threads();
    int step = size / thread_num;
    int s = 0;
    int e = step;
    for (i = 0; i < size / 2; i++)
    {
        #pragma omp parallel for private(j,s,e,temp)
        for (j = s; j < e; j += 2)
            if (data[j] > data[j + 1])
                swap(&data[j], &data[j + 1]);
        #pragma omp parallel for private(j,s,e,temp)
        for (j = 1 + s; j < e; j += 2)
            if (data[j] > data[j + 1])
                swap(&data[j], &data[j + 1]);
        s += step;
        e += step;
        if (e > size) e = size;
    }
}


int main()
{
    clock_t start, end;
    double total;
    int i;
    start = clock();  //获取开始时间

    const int DataSize = 1e5;
    int data[DataSize];
    CreateData(data, DataSize);
    bubbleSort(data, DataSize);
    // for (int i = 0; i < DataSize; i++) {
    //     printf("%d ", data[i]);
    // }
    // puts("\n");
    #pragma omp parallel 
    {
        #pragma omp barrier //等待所有进程结束
    }
    
    end = clock();  //获取结束时间
    total = (double)(end - start)/CLOCKS_PER_SEC;  //计算耗时
    printf("Total time: %f seconds\n", total);

    return 0;
}
